package com.facebookproject.graph.showdialogdetail;

import static com.facebookproject.Const.APP_FB_ID;
import static com.facebookproject.Const.APP_PATH;
import static com.facebookproject.Const.APP_PHOTO;
import static com.facebookproject.Const.URL_GRAPH;
import static com.facebookproject.Const.URL_PHOTO_SIZE_200;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;
import com.facebookproject.R;
import com.facebookproject.loginfb.LoginFacebook;
public class ShowDialog {
	private String fPath = Environment.getExternalStorageDirectory().getAbsolutePath() + APP_PATH + APP_PHOTO;
	private JSONObject json = null;
	private TextView t_name,
	t_username,
	t_birthday,
	t_gender,
	t_hometown,
	t_location,
	t_work,
	t_edu,
	t_email,
	t_website,
	t_relationship,
	t_languages,
	t_quotes,
	t_bio;
	private ImageView img;
	private final Dialog dialog;

	@SuppressWarnings("deprecation")
	private Facebook facebook = new Facebook(APP_FB_ID);
	Context context;
	@SuppressLint("CutPasteId")
	public ShowDialog(String id, Context context) {
		this.context = context;
		facebook = new LoginFacebook().login(context,facebook);
		dialog = new Dialog(context){
			 @Override
			  public boolean onTouchEvent(MotionEvent event) {
			    dialog.dismiss();
			    return true;
			  }
		};
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_about);
		dialog.setCanceledOnTouchOutside(true);
		int width;
		if(context.getResources().getDisplayMetrics().widthPixels<=500)
			width = (int)(context.getResources().getDisplayMetrics().widthPixels-40);
		else{width = 460;}
		LinearLayout dl_layout = (LinearLayout)dialog.findViewById(R.id.dl_layout_a);
		dl_layout.setLayoutParams(new LinearLayout.LayoutParams(width, LinearLayout.LayoutParams.WRAP_CONTENT));

		setid();
		getJson(id);
		setimage();
		setvalues();
		dialog.show();
			
		
		ImageButton dialogButton = (ImageButton) dialog.findViewById(R.id.dl_btn_close);
		dialogButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
		
	}


	@SuppressWarnings("deprecation")
	private void getJson(String id) {
		try {
			Bundle params = new Bundle();
			params.putString("access_token", facebook.getAccessToken());
			if(facebook.isSessionValid())
				json = Util.parseJson(facebook.request(id,params, "GET"));
			else{
				dialog.cancel();
			}
			
		} catch (FacebookError e) {
			Toast.makeText(context, "FacebookError "+getClass().getName(), Toast.LENGTH_SHORT).show();
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			Toast.makeText(context, "FileNotFoundException "+getClass().getName(), Toast.LENGTH_SHORT).show();
			e.printStackTrace();
		} catch (MalformedURLException e) {
			Toast.makeText(context, "MalformedURLException "+getClass().getName(), Toast.LENGTH_SHORT).show();
			e.printStackTrace();
		} catch (JSONException e) {
			Toast.makeText(context, "JSONExceptio "+getClass().getName(), Toast.LENGTH_SHORT).show();
			e.printStackTrace();
		} catch (IOException e) {
			Toast.makeText(context, "IOException "+getClass().getName(), Toast.LENGTH_SHORT).show();
			e.printStackTrace();
		}
	}
	private void setimage() {
		try {
			String img_preload = fPath + "/profilespictures_" + json.getString("id") +".jpg";
			File check_exists = new File(fPath, "profilespictures_" + json.getString("id") +".jpg");
			if(check_exists.exists()){
				Bitmap bmp_preload = BitmapFactory.decodeFile(img_preload);
				if(bmp_preload!=null)
					img.setImageBitmap(bmp_preload);
				else{
					dlimage();
					setimage();
				}
			}
			else{
				dlimage();
				setimage();
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	private void dlimage(){
		try {
			URL url = new URL(URL_GRAPH+ json.getString("id") + URL_PHOTO_SIZE_200);
			Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
			File dir = new File(fPath);
			if (!dir.exists()) 
				dir.mkdirs();
			OutputStream fOut = null;
			File file = new File(fPath, "profilespictures_" + json.getString("id") +".jpg");
			if(!file.exists())
				file.createNewFile();
			fOut = new FileOutputStream(file);
			bmp.compress(Bitmap.CompressFormat.PNG, 100, fOut);
			fOut.flush();
			fOut.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	private void setvalues() {
		try {
			/**
			if(json.has(""))t_.setText(" : " + json.getString(""));
			else {t_.setVisibility(View.GONE);}
			 **/

			if(json.has("name"))t_name.setText(" " + json.getString("name"));
			if(json.has("username"))t_username.setText(json.getString("username"));
			if(json.has("birthday"))t_birthday.setText(json.getString("birthday"));
			if(json.has("gender"))t_gender.setText(json.getString("gender"));

			if(json.has("hometown"))t_hometown.setText("Hometown : " + json.getJSONObject("hometown").getString("name")+".");
			else {t_hometown.setVisibility(View.GONE);}

			if(json.has("location"))t_location.setText("Lives : " + json.getJSONObject("location").getString("name")+".");
			else {t_location.setVisibility(View.GONE);}

			if(json.has("email"))t_email.setText("Email : " + json.getString("email"));
			else {t_email.setVisibility(View.GONE);}

			if(json.has("website"))t_website.setText("Website : " + json.getString("website"));
			else {t_website.setVisibility(View.GONE);}

			if(json.has("quotes"))t_quotes.setText("Quotes : \"" + json.getString("quotes")+"\"");
			else {t_quotes.setVisibility(View.GONE);}

			if(json.has("bio"))t_bio.setText("About me : " + json.getString("bio"));
			else {t_bio.setVisibility(View.GONE);}

			if(json.has("relationship_status")){
				String rel="Relationship Status: " + json.getString("relationship_status");
				if(json.has("significant_other"))
					rel+= " with "+json.getJSONObject("significant_other").getString("name");
				t_relationship.setText(rel+".");

			}else {t_relationship.setVisibility(View.GONE);}

			if(json.has("languages")){
				String lang = "";
				JSONArray ja = json.getJSONArray("languages");
				for(int i=0;i<ja.length();i++){
					lang = lang + ja.getJSONObject(i).getString("name");
					if((i+1)==ja.length()){
						lang+= ".";
					}else{
						lang+=", ";
					}
				}
				t_languages.setText("Languages : " + lang);
			}else {t_languages.setVisibility(View.GONE);}

			if(json.has("work")){
				String works = "Work : ";
				JSONArray ja = json.getJSONArray("work");
				for(int i=0;i<ja.length();i++){
					if(ja.getJSONObject(i).has("position"))works+=ja.getJSONObject(i).getJSONObject("position").getString("name");
					if(ja.getJSONObject(i).has("position")&&ja.getJSONObject(i).has("employer"))works+=" at ";
					if(ja.getJSONObject(i).has("employer"))works+= ja.getJSONObject(i).getJSONObject("employer").getString("name");
					if(ja.getJSONObject(i).has("location"))works+=", " + ja.getJSONObject(i).getJSONObject("location").getString("name");
					works+=".";
					if(i<(ja.length()-1))works+="\n\t\t ";
				}
				t_work.setText(works);
			}else {t_work.setVisibility(View.GONE);}

			if(json.has("education")){
				String ed = "Study : ";
				JSONArray ja = json.getJSONArray("education");
				for(int i=(ja.length()-1);i>=0;i--){
					if(ja.getJSONObject(i).has("classes"))ed += ja.getJSONObject(i).getJSONArray("classes").getJSONObject(0).getString("name") + "-";
					if(ja.getJSONObject(i).has("concentration"))ed += ja.getJSONObject(i).getJSONArray("concentration").getJSONObject(0).getString("name") + "-";
					if(ja.getJSONObject(i).has("school"))ed +=ja.getJSONObject(i).getJSONObject("school").getString("name");
					if(ja.getJSONObject(i).has("type"))ed +=" " + ja.getJSONObject(i).getString("type");
					if(ja.getJSONObject(i).has("year"))ed +=", " + ja.getJSONObject(i).getJSONObject("year").getString("name");
					ed+=".";
					if(i>0)ed+="\n\t\t ";
				}
				t_edu.setText(ed);
			}else {t_edu.setVisibility(View.GONE);}
		} catch (JSONException e) {
			dialog.dismiss();
		}
	}

	private void setid() {
		t_name				= (TextView)dialog.findViewById(R.id.dl_txt_name);
		t_username			= (TextView)dialog.findViewById(R.id.dl_txt_username);
		t_gender			= (TextView)dialog.findViewById(R.id.dl_txt_gender);
		t_birthday			= (TextView)dialog.findViewById(R.id.dl_txt_birthday);
		t_hometown			= (TextView)dialog.findViewById(R.id.dl_txt_hometown);
		t_location			= (TextView)dialog.findViewById(R.id.dl_txt_location);
		t_work				= (TextView)dialog.findViewById(R.id.dl_txt_work);
		t_edu				= (TextView)dialog.findViewById(R.id.dl_txt_edu);
		t_email				= (TextView)dialog.findViewById(R.id.dl_txt_email);
		t_website			= (TextView)dialog.findViewById(R.id.dl_txt_website);
		t_relationship		= (TextView)dialog.findViewById(R.id.dl_txt_relationship);
		t_languages			= (TextView)dialog.findViewById(R.id.dl_txt_languages);
		t_quotes			= (TextView)dialog.findViewById(R.id.dl_txt_quotes);
		t_bio				= (TextView)dialog.findViewById(R.id.dl_txt_bio);
		img 				= (ImageView)dialog.findViewById(R.id.dl_img_picture);
	}
	

}
